/*
 ** writen by hanv
 ** n2.vietha@gmail.com
 */
package vn.vng.research.fsd;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import vn.vng.research.fsd.da.ProfilesDA;
import vn.vng.research.fsd.da.SchoolRefinerDA;
import vn.vng.research.fsd.data.SearchCache;

public class Configuration {
	private static final String CONFIG_PATH = "./server-config/config.properties";
	private static final String SEARCH_ID_PATH = "./server-config/search-id.properties";

	public static Properties properties;

	private static long NEXT_ID = 0;

	//
	// load config
	//
	public static void load() {
		try {
			properties = new Properties();
			properties.load(new FileInputStream(CONFIG_PATH));

			loadSearchIDConfig();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	//
	// Paths
	//
	public static String loadProfilesPath() {
		try {
			return properties.getProperty("PROFILES_PATH");
		} catch (Exception e) {
			// TODO: handle exception
			// return default
			return "./data/profiles";
		}
	}

	public static String loadIndexPath() {
		try {
			return properties.getProperty("INDEX_PATH");
		} catch (Exception e) {
			// TODO: handle exception
			// return default
			return "./data/index";
		}
	}

	public static String loadSchoolRefinePath() {
		try {
			return properties.getProperty("SCHOOL_REFINE_PATH");
		} catch (Exception e) {
			// TODO: handle exception
			// return default
			return "./data/refiners/school_refine";
		}
	}

	//
	// search id
	//

	public static void loadSearchIDConfig(){
		Properties sidProperties = new Properties();
		try {
			sidProperties.load(new FileInputStream(SEARCH_ID_PATH));

			NEXT_ID = (Long.parseLong(sidProperties.getProperty("last_id")) + 1);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public static long nextSearchID() {
		long nextID = (NEXT_ID++) % (Long.MAX_VALUE - 107);
		Properties sidProperties = new Properties();
		try {
			File searchIDFile = new File(SEARCH_ID_PATH);
			FileInputStream fis = new FileInputStream(searchIDFile);			
			sidProperties.load(fis);
			fis.close();
			
			sidProperties.setProperty("last_id", "" + nextID);
			
			FileOutputStream fos = new FileOutputStream(searchIDFile);
			sidProperties.store(fos, "update last id");			
			fos.close();
			
			return nextID;
		} catch (Exception e) {
			// TODO: handle exception
			return nextID;
		} finally {
			
		}
	}

	//
	// cache
	//

	public static int loadSearchCacheLimit() {
		try {
			return Integer.parseInt(properties.getProperty("cache_limit"));
		} catch (Exception e) {
			// TODO: handle exception
			return 107;
		}
	}
	
	//
	// Port
	//
	public static int loadPort(String service){
		try {
			return Integer.parseInt(properties.getProperty(service+"_service_port"));
		} catch (Exception e) {
			// TODO: handle exception
			return 10700;
		}
	}
}
